package com.meng.thrift.server.thrift.test;

import com.meng.thrift.server.thrift.inter.HelloWorldService;
import com.meng.thrift.server.thrift.inter_impl.HwServciceImpl;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Thrift线程 测试用的
 *
 * @author MENG
 * @version 2017/10/31
 * @see
 */
public class ThriftThread implements Runnable
{

    private Logger logger = LoggerFactory.getLogger(ThriftThread.class);

    private static final int SERVER_PORT = 8191;

    // 关联处理器与Service服务的实现
    private TProcessor tprocessor;


    public ThriftThread(TProcessor tprocessor)
    {
        this.tprocessor = tprocessor;
    }

    @Override
    public void run()
    {
        try
        {
            // 非阻塞式的，配合TFramedTransport使用
            TNonblockingServerSocket tNonblockingServerSocket = new TNonblockingServerSocket(SERVER_PORT);

            // 目前Thrift提供的最高级的模式，可并发处理客户端请求
            TThreadedSelectorServer.Args thhsArgs = new TThreadedSelectorServer.Args(tNonblockingServerSocket);

            thhsArgs.processor(tprocessor);

            // // 和客户端一致    设置传输工厂，使用非阻塞方式，按块的大小进行传输，类似于Java中的NIO
            thhsArgs.transportFactory(new TFramedTransport.Factory());
            thhsArgs.protocolFactory(new TBinaryProtocol.Factory());


            TServer server = new TThreadedSelectorServer(thhsArgs);

            server.serve();

        }
        catch (TTransportException e)
        {
            logger.error("创建Thrift Server出错",e);
        }

    }

    public static void main(String[] args)
    {
        //执行thrift  server端线程
        TProcessor tprocessor = new HelloWorldService.Processor<HelloWorldService.Iface>(new HwServciceImpl());

        ThriftThread thriftThread = new ThriftThread(tprocessor);

        Thread thread = new Thread(thriftThread);

        thread.start();
    }
}
